package cn.mxz.xmu.robots.basic;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @description robots底层工具，各类包的子utlis继承此工具
 * 
 * @author cuizhennan <cuizhennan@mouge.wang>
 * @since 2015-4-14
 */
public final class RobotsUtlis
{
	public static String getTokenCaptchaKey(String key)
	{
		return "token_view_" + key;
	}

	public static String getWebRequestKey(String key)
	{
		return "webrequest_url_" + key;
	}

	/**
	 * 正则匹配
	 * 
	 * @param str
	 *            要匹配的字符串
	 * @param regex
	 *            匹配的规则
	 * @return 匹配成功的字符串
	 */
	public static String regexMatch(String str, String regex)
	{
		Pattern regexPat = Pattern.compile(regex);
		Matcher regexMat = regexPat.matcher(str);
		if (regexMat.find())
		{
			return regexMat.group(1);
		}
		return "";
	}

	/**
	 * 将字符串进行URLEncode加密
	 * 
	 * @param input
	 *            加密之前的字符串
	 * @return 加密之后的字符串
	 */
	public static String urlEncode(String input)
	{
		try
		{
			return URLEncoder.encode(input, "UTF-8");

		}
		catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 格式化　WebRequest　的URL
	 * 
	 * @param urlParams
	 * @return
	 */
	public static URL getURL(String urlParams)
	{
		URL url = null;

		try
		{
			if (!urlParams.equals("") || urlParams != null)
			{
				url = new URL(urlParams);
			}
		}
		catch (MalformedURLException e)
		{
			e.printStackTrace();
		}
		return url;
	}

	/**
	 * 正则 判断一个字符串，是否存在此（elements）元素
	 * 
	 * @param elements
	 * @param regex
	 * @return true 或　false
	 */
	public static boolean isElemetns(String elements, String regex)
	{
		boolean isFlag = false;
		Pattern regexPat = Pattern.compile(regex);
		Matcher regexMat = regexPat.matcher(elements);
		if (regexMat.find())
		{
			isFlag = true;
		}
		return isFlag;
	}

	/**
	 * 将字符串进行URLEncode加密
	 * 
	 * @param input
	 *            加密之前的字符串
	 * @return 加密之后的字符串
	 */
	public static String urlChineseEncode(String input)
	{
		try
		{
			return URLEncoder.encode(input, "gb2312");
		}
		catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		}
		return "";
	}

}
